package com.example.freeengine.wallpaper.fragment.cyclerefresh.albumlist;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.PopupMenu;
import androidx.lifecycle.LifecycleOwner;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;

import com.example.freeengine.R;
import com.example.freeengine.wallpaper.alarm.MyAlarmWorker;
import com.example.freeengine.wallpaper.constants.WallPaperUpdateStrategy;
import com.example.freeengine.wallpaper.fragment.WallPaperViewModel;
import com.example.freeengine.wallpaper.fragment.cyclerefresh.AlbumInfo;
import com.example.freeengine.wallpaper.persistence.entity.WallPaperCycleRefreshAlbum;
import com.example.freeengine.wallpaper.persistence.entity.WallPaperCycleRefreshAlbumItem;
import com.example.freeengine.wallpaper.persistence.repository.WallPaperCycleRefreshRepository;
import com.example.freeengine.wallpaper.service.MyWallPaperService;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;

/**
 * @author Terry Deng
 */
public class AlbumListAdapter extends ListAdapter<AlbumInfo, AlbumListAdapter.MyViewHolder> {

    private static final String TAG = AlbumListAdapter.class.getSimpleName();
    Context context;
    LifecycleOwner lifecycleOwner;

    WallPaperViewModel wallPaperViewModel;
    WallPaperCycleRefreshRepository wallPaperCycleRefreshRepository;

    static DiffUtil.ItemCallback DIFF_CALLBACK = new DiffUtil.ItemCallback<AlbumInfo>() {
        @Override
        public boolean areItemsTheSame(@NonNull AlbumInfo oldItem, @NonNull AlbumInfo newItem) {
            return oldItem.getAlbumId().equals(newItem.getAlbumId());
        }

        @Override
        public boolean areContentsTheSame(@NonNull AlbumInfo oldItem, @NonNull AlbumInfo newItem) {
            return oldItem.equals(newItem);
        }
    };

    public AlbumListAdapter(Context context){
        super(DIFF_CALLBACK);
        this.context = context;
    }

    public AlbumListAdapter(Context context, WallPaperViewModel wallPaperViewModel){
        super(DIFF_CALLBACK);
        this.context = context;
        this.wallPaperViewModel = wallPaperViewModel;
    }

    public AlbumListAdapter(Context context, WallPaperViewModel wallPaperViewModel, WallPaperCycleRefreshRepository wallPaperCycleRefreshRepository){
        super(DIFF_CALLBACK);
        this.context = context;
        this.wallPaperViewModel = wallPaperViewModel;
        this.wallPaperCycleRefreshRepository = wallPaperCycleRefreshRepository;
    }

    public AlbumListAdapter(Context context, WallPaperViewModel wallPaperViewModel,
                            WallPaperCycleRefreshRepository wallPaperCycleRefreshRepository,
                            LifecycleOwner lifecycleOwner){
        super(DIFF_CALLBACK);
        this.context = context;
        this.wallPaperViewModel = wallPaperViewModel;
        this.wallPaperCycleRefreshRepository = wallPaperCycleRefreshRepository;
        this.lifecycleOwner = lifecycleOwner;
    }

    @NonNull
    @NotNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull @NotNull ViewGroup parent, int viewType) {
        LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
        return new MyViewHolder(layoutInflater.inflate(R.layout.wallpaper_cyclerefresh_album_list_item, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull @NotNull MyViewHolder holder, int position) {

        // Drawable drawable = Drawable.createFromPath(pictureInfoList.get(position).getPath());
        // holder.ivPicture.getLayoutParams().width = drawable.getIntrinsicWidth();
        // holder.ivPicture.getLayoutParams().height = 200;

        AlbumInfo data = getItem(position);

        holder.tvAlbumItemCount.setText(String.valueOf(data.getItemCount()));
        holder.tvAlbumItemName.setText(data.getName());
        if (data.getItemCount() > 0 && data.getPreviewPath() != null){
            holder.ivPicture.setImageURI(Uri.parse(data.getPreviewPath()));
        }
        holder.btnUsing.setChecked(data.isUsing());

        holder.ivItemMenu.setOnClickListener(v -> {
            PopupMenu popup = new PopupMenu(context, v);
            MenuInflater inflater = popup.getMenuInflater();
            inflater.inflate(R.menu.menu_wallpaper_cyclerefresh_album_list_item, popup.getMenu());
            popup.show();

            popup.setOnMenuItemClickListener(item -> {

                switch (item.getItemId()){
                    case R.id.wallpaper_cyclerefresh_album_picture_list: {
                        NavController navController = Navigation.findNavController(v);
                        Bundle bundle = new Bundle();
                        bundle.putLong("albumId", data.getAlbumId());
                        navController.navigate(R.id.action_wallPaperCycleRefreshFragment_to_albumPictureListFragment, bundle);
                        return true;
                    }
                    case R.id.wallpaper_cyclerefresh_album_delete: {
                        new AlertDialog.Builder(context)
                                .setTitle("提示")
                                .setMessage("是否删除图集?")
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        try {
                                            // 删除数据库中的信息
                                            List<WallPaperCycleRefreshAlbumItem> wallPaperCycleRefreshAlbumItemList = wallPaperCycleRefreshRepository.findAllByAlbumId(data.getAlbumId());
                                            wallPaperCycleRefreshRepository.deleteAlbum(data.getWallPaperCycleRefreshAlbum());
                                            // 删除本地文件
                                            for (WallPaperCycleRefreshAlbumItem wallPaperCycleRefreshAlbumItem : wallPaperCycleRefreshAlbumItemList){
                                                File f = new File(wallPaperCycleRefreshAlbumItem.getPicturePath());
                                                if (f.exists()){
                                                    f.delete();
                                                }
                                            }
                                            // 正在使用该图集
                                            if (holder.btnUsing.isChecked()){
                                                // wallPaperViewModel.stopWallPaperUpdateWork(context);
                                                new MyAlarmWorker.Builder(context).stopAlarm();
                                            }
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }
                                })
                                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                    }
                                })
                                .show();
                        return true;
                    }
                    case R.id.wallpaper_cyclerefresh_album_update_frequency:{

                        if (!holder.btnUsing.isChecked()){
                            new AlertDialog.Builder(context)
                                    .setTitle("提示")
                                    .setMessage("请先启用该图集")
                                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {

                                        }
                                    })
                                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                        }
                                    })
                                    .show();
                            return true;
                        }

                        AlertDialog.Builder builder = new AlertDialog.Builder(context);
                        LayoutInflater  layoutInflater = LayoutInflater.from(context);
                        View view = layoutInflater.inflate(R.layout.wallpaper_cyclerefresh_album_picture_update_frequency, null);

                        builder.setView(view);
                        Button btnCancel = view.findViewById(R.id.btn_wallpaper_cyclerefresh_album_frequency_cancel);
                        Button btnOk = view.findViewById(R.id.btn_wallpaper_cyclerefresh_album_frequency_ok);

                        Spinner spinner = view.findViewById(R.id.spinner_wallpaper_cyclerefresh);
                        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(context,
                                R.array.wallpaper_cyclerefresh_frequency, android.R.layout.simple_spinner_item);
                        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        spinner.setAdapter(adapter);

                        spinner.setSelection(wallPaperViewModel.getWallPaperCycleRefreshFrequency(context).intValue() - 1);

                        AlertDialog dialog = builder.show();
                        btnCancel.setOnClickListener(v1 -> {
                            dialog.dismiss();
                        });

                        btnOk.setOnClickListener(v1 -> {
                            long frequency = spinner.getSelectedItemId() + 1;
                            Log.i(TAG, "change cyclerefresh frequency to " + frequency);
                            wallPaperViewModel.setWallPaperWallPaperCycleRefreshFrequency(context, frequency);
                            // wallPaperViewModel.startWallPaperCycleRefreshUpdateWork(context, lifecycleOwner, frequency);
                            new MyAlarmWorker.Builder(context).startCycleRefreshRefreshAlarm(frequency * 60 * 1000L);
                            dialog.dismiss();
                        });
                        return true;
                    }
                    default:
                        return false;
                }
            });
        });

        holder.btnUsing.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (data.getItemCount() < 1){
                    new AlertDialog.Builder(context)
                            .setTitle("提示")
                            .setMessage("请先添加图片")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                }
                            })
                            .show();
                    holder.btnUsing.toggle();
                    return;
                }

                Log.i(TAG, "onClick: ");
                if (holder.btnUsing.isChecked()){
                    new AlertDialog.Builder(context)
                            .setTitle("提示")
                            .setMessage("是否确定将壁纸设置为从该图集循环更新?")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    wallPaperViewModel.setWallPaperUpdateStrategyInfo(WallPaperUpdateStrategy.FROM_CYCLEREFRESH,
                                            context, String.valueOf(data.getAlbumId()));
                                    wallPaperViewModel.setCycleRefreshAlbumChange(data.getAlbumId());

                                    // wallPaperViewModel.startWallPaperCycleRefreshUpdateWork(context, lifecycleOwner);
                                    new MyAlarmWorker.Builder(context).startCycleRefreshRefreshAlarm(1 * 60 * 1000L);
                                    wallPaperViewModel.setWallPaperWallPaperCycleRefreshFrequency(context, 1L);

                                    wallPaperViewModel.setCycleRefreshAlbumItemInfo(context, 0L);
                                }
                            })
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    holder.btnUsing.toggle();
                                }
                            })
                            .setCancelable(false)
                            .show();
                }else {
                    new AlertDialog.Builder(context)
                            .setTitle("提示")
                            .setMessage("是否取消壁纸从该图集循环更新?")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    wallPaperViewModel.setWallPaperUpdateStrategyInfo(WallPaperUpdateStrategy.NOT_SET,
                                            context, "");
                                    wallPaperViewModel.setCycleRefreshAlbumChange(0L);

                                    // wallPaperViewModel.stopWallPaperUpdateWork(context);
                                    new MyAlarmWorker.Builder(context).stopAlarm();
                                }
                            })
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    holder.btnUsing.toggle();
                                }
                            })
                            .setCancelable(false)
                            .show();

                }
            }
        });

    }


    class MyViewHolder extends RecyclerView.ViewHolder {

        public ImageView ivPicture, ivItemMenu;
        public Switch btnUsing;
        public TextView tvAlbumItemCount, tvAlbumItemName;

        public MyViewHolder(@NonNull @NotNull View itemView) {
            super(itemView);
            ivPicture = itemView.findViewById(R.id.iv_picture);
            ivItemMenu = itemView.findViewById(R.id.iv_item_menu);
            btnUsing = itemView.findViewById(R.id.btnUsing);
            tvAlbumItemCount = itemView.findViewById(R.id.tv_album_item_count);
            tvAlbumItemName = itemView.findViewById(R.id.tv_album_item_name);
        }
    }

}
